﻿using Microsoft.Data.SqlClient;
using System.Data;

namespace SqlserverPool.Client
{
    public class Repository<T> where T : IEntity
    {
        private string connectionString;

        public Repository(string connectionString)
        {
            this.connectionString = connectionString;
        }

        public async Task<int> ExecuteNonQueryAsync(string query, Action<SqlCommand> addParameters)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                await connection.OpenAsync();
                SqlCommand command = new SqlCommand(query, connection);
                addParameters(command);
                return await command.ExecuteNonQueryAsync();
            }
        }

        public async Task<DataTable> ExecuteQueryAsync(string sql, SqlParameter[] parameters)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                await connection.OpenAsync();
                SqlCommand command = new SqlCommand(sql, connection);
                command.Parameters.AddRange(parameters);
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);
                return dataTable;
            }
        }
    }
}
